package geoway.bmf.keycloak.utils;

import org.keycloak.KeycloakSecurityContext;
import org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken;
import org.keycloak.representations.AccessToken;
import org.keycloak.representations.IDToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

import static java.util.Optional.empty;
import static java.util.Optional.of;

/**
 * @author yrt
 * @description
 * @date 2022/11/15 10:17
 */
public final class KeycloakSecurityUtil {
    private KeycloakSecurityUtil() {

    }

    public static KeycloakSecurityContext getKeycloakSecurityContext(HttpServletRequest request) {
        return (KeycloakSecurityContext) request.getAttribute(KeycloakSecurityContext.class.getName());
    }

    public static IDToken getIDToken(HttpServletRequest request) {
        return KeycloakSecurityUtil.getKeycloakSecurityContext(request).getIdToken();
    }

    public static Optional<AccessToken> OkHttpUtilgetAccessToken(HttpServletRequest request) {
        KeycloakSecurityContext credentials = getKeycloakSecurityContext(request);
        return of(credentials.getToken());
    }

}
